package com.xywy.bloodandroid.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.adapter.ExpertShareAdapter;
import com.xywy.bloodandroid.bean.ExpertArtail;
import com.xywy.bloodandroid.util.Constants;
import com.xywy.bloodandroid.util.JsonUtil;
import com.xywy.bloodandroid.util.LogUtil;
import com.xywy.bloodandroid.util.NetUtil;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.GetRequest;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.VolleyManager;

public class ExpertExperienceShareFragement extends Fragment implements OnScrollListener {

	protected static final int DOCTORARTAILERROR = -3;
	protected static final int DOCTORARTAILSUCESS = -4;
	private ListView listview;
	private ExpertShareAdapter adapter;
	private LinearLayout doctor_charch_rel;
	private String id;
	private int page=1;
	private int pageCount=20;
	private boolean isLoadMore = true;
	protected ProgressDialog waittingDialog;
    private List<ExpertArtail> list;
    
    private int visibleLastIndex = 0;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragement_doctorchurch, null);
		initView(view);
		initListener();
		initdata();
		
		return view;
	}

	private void initdata() {
		
		
		getExpertArtileList(id);
		
	}
    
	private void getExpertArtileList(String id) {
		isLoadMore=true;
		final Message msg = Message.obtain();
		GetRequest<String>  getRequest=new GetRequest<String>(Constants.getUrl("zhuanjia", "Article")+"&source=cdsb"+"&id="+id+"&page="+page+"&size="+pageCount, String.class, new OnVolleyResponseListener<String>() {

			@Override
			public void onError(VolleyError volleyError) {
				LogUtil.i(".....Error.......", volleyError + "");

				msg.what = DOCTORARTAILERROR;
				handler.sendMessage(msg);
			}

			@Override
			public void onSuccess(String response) {
				
				
				JSONObject object;
				try {
					object = new JSONObject(response);
					int code=object.optInt("code"); 
					String msg1 = object.optString("msg");
				if(code==10000){
					ParseJson(object);
					
					msg.what = DOCTORARTAILSUCESS;
					handler.sendMessage(msg);
				}else{
					UIUtil.showToast(getActivity(), msg1);
				}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
		getRequest.setIsParseJson(false);
		if (NetUtil.hasNetwork(getActivity())) {
			if(page==1)
			waitingDialog(getActivity(), getActivity().getResources()
					.getString(R.string.request));
			VolleyManager.addRequest(getRequest, getActivity());
		} else {
			UIUtil.showToast(getActivity(), getActivity().getResources()
					.getString(R.string.not_network));
			UIUtil.DissDialog(getActivity(), waittingDialog);
		}
	}

	 
	 private void ParseJson(JSONObject object){
		 if (object != null) {
				String data = object.optString("data");
				System.out.println("huoqu de data.."+data);
				if(data.length()>0)
				list.addAll((List<ExpertArtail>) JsonUtil.parseJsonToList(data,
						new TypeToken<List<ExpertArtail>>() {
						}.getType()));
			}
	 }
	public void waitingDialog(Context context, String message) {
		if (waittingDialog == null)
			waittingDialog = new ProgressDialog(context);
		waittingDialog.setCanceledOnTouchOutside(false);//
		waittingDialog.setMessage(message);
		waittingDialog.show();
	}
	private void initListener() {
		listview.setOnScrollListener(this);
	}

	private void initView(View view) {
		id = getArguments().getString("expertid");
		
        
		listview = (ListView) view.findViewById(R.id.famous_doctor_listview);
		listview.setDividerHeight(0);
		list = new ArrayList<ExpertArtail>();
		
		

		list_footer = (LinearLayout)getActivity().getLayoutInflater().inflate(
				R.layout.list_footer, null);

		list_footer.setVisibility(View.GONE);
		tv_msg = (TextView) list_footer.findViewById(R.id.tv_msg);
		loading = (LinearLayout) list_footer.findViewById(R.id.loading);
		listview.addFooterView(list_footer);
		
	
		adapter = new ExpertShareAdapter(getActivity(), list,id);
		listview .setAdapter(adapter);
		
	}  
	
	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case DOCTORARTAILERROR:
				UIUtil.DissDialog(getActivity(), waittingDialog);
				UIUtil.showToast(getActivity(), getActivity().getResources()
						.getString(R.string.network_slow));
				break;
			case DOCTORARTAILSUCESS:
				UIUtil.DissDialog(getActivity(), waittingDialog);
				
				if(list.size()>0&list.size()<=pageCount*page&pageCount>0){
					list_footer.setVisibility(View.VISIBLE);
					tv_msg.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
					}
				if(list.size()<20||list.size()<pageCount*page){
					listview.removeFooterView(list_footer);
					
				}
				
				
				
				adapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		}
	};
	private LinearLayout list_footer;
	private TextView tv_msg;
	private LinearLayout loading;
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

		int itemsLastIndex = adapter.getCount(); // 
		int lastIndex = itemsLastIndex + 1; //
		if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
				&& visibleLastIndex == lastIndex) {
			if (isLoadMore) {
				isLoadMore = false;
				page++;
				Log.i("pageNo", "..." + page + "......");
				tv_msg.setVisibility(View.GONE);
				loading.setVisibility(View.VISIBLE);
               getExpertArtileList(id);
			}
		}
	
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		visibleLastIndex = firstVisibleItem + visibleItemCount;
	}
	 @Override
     public void onDestroy() {
	super.onDestroy();
	VolleyManager.cancelRequest(getActivity());
    }
}
